package com.insmess.speech.service.impl;

import com.insmess.speech.common.api.CommonResult;
import com.insmess.speech.common.util.InsmessFileUtils;
import com.insmess.speech.dto.AsrDto;
import com.insmess.speech.sdk.dto.AsrResponseDto;
import com.insmess.speech.sdk.template.FfmpegTemplate;
import com.insmess.speech.sdk.template.InsmessAsrTemplate;
import com.insmess.speech.service.AsrService;
import com.insmess.speech.service.TextService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.UUID;

@Service
@Slf4j
public class AsrServiceImpl implements AsrService {
    @Autowired
    private FfmpegTemplate ffmpegTemplate;

    @Autowired
    private InsmessAsrTemplate insmessAsrTemplate;

    @Autowired
    private TextService textService;
    @SneakyThrows
    @Override
    public String asr(MultipartFile file) {
        File tmpAudioFile = InsmessFileUtils.getTmpFile(file);
        //进行语音转换
        return asr(tmpAudioFile);
    }

    @Override
    public String asr(File file, AsrDto asrDto) {
        InsmessFileUtils.checkFormat(file);
        //将语音文件转成wav
        File audioFile = ffmpegTemplate.formatWav(file);
        //进行语音识别
        AsrResponseDto asrResponseDto = insmessAsrTemplate.asrRequest(audioFile.getAbsolutePath());
        if (!asrResponseDto.getCode().equals(200)) {
            throw new RuntimeException(asrResponseDto.toString());
        }
        String content = asrResponseDto.getResult().getTranscription();
        //后期处理
        //添加标点
        if (asrDto == null || asrDto.getPunc() == null || asrDto.getPunc().equals(1)) {
            content = textService.punctuation(content);
        }
        //添加替换热词
        if (asrDto == null || asrDto.getHotWord() == null || asrDto.getHotWord().equals(1)) {
            content = textService.hotWord(content);
        }
        //添加替换敏感词
        if (asrDto == null || asrDto.getHotWord() == null || asrDto.getHotWord().equals(1)) {
            content = textService.sensitiveFilter(content);
        }
        return content;
    }

    @Override
    public String asr(File file) {
        return asr(file, null);
    }


}
